package com.engine4cloud.tdf.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.engine4cloud.tdf.admin.api.dto.AreaCreateDTO;
import com.engine4cloud.tdf.admin.api.dto.AreaQueryDTO;
import com.engine4cloud.tdf.admin.api.dto.AreaUpdateDTO;
import com.engine4cloud.tdf.admin.api.entity.SysAreaEntity;
import com.engine4cloud.tdf.admin.api.vo.AreaResultVO;
import com.engine4cloud.tdf.admin.convert.SysAreaConvert;
import com.engine4cloud.tdf.admin.mapper.SysAreaMapper;
import com.engine4cloud.tdf.admin.service.SysAreaService;
import com.engine4cloud.tdf.common.core.exception.ValidateCodeException;
import com.engine4cloud.tdf.common.data.web.query.Pages;
import com.engine4cloud.tdf.common.data.web.query.Queries;
import com.engine4cloud.tdf.common.data.web.response.PageInfo;
import com.engine4cloud.tdf.common.data.web.response.Params;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;


/**
 * 行政区划
 *
 * @author lbw
 * @date 2024-02-16 22:40:06
 */
@Service
public class SysAreaServiceImpl extends ServiceImpl<SysAreaMapper, SysAreaEntity> implements SysAreaService {

    @Override
    public PageInfo<AreaResultVO> pageList(Params pageable, AreaQueryDTO dto) {
        IPage<AreaResultVO> pages = this.baseMapper.pageList(Pages.page(pageable), dto);
        return Pages.convert(pages);
    }

    @Override
    public AreaResultVO findById(Long id) {
        return SysAreaConvert.INSTANCE.convert(this.getById(id));
    }

    @Override
    public Boolean create(AreaCreateDTO dto) {
        AreaQueryDTO query = new AreaQueryDTO(dto.getPcode());
        SysAreaEntity father = Optional.ofNullable(this.getOne(wrapper(query)))
                .orElseThrow(() -> new ValidateCodeException("父地区不存在"));

        boolean unique = this.checkUniqueByAreaCode(null, dto.getCode());
        if (!unique) {
            throw new ValidateCodeException("地区编码不唯一");
        }
        SysAreaEntity entity = SysAreaConvert.INSTANCE.create(dto);
        return this.save(entity);
    }

    @Override
    public Boolean update(AreaUpdateDTO dto) {
        AreaQueryDTO query = new AreaQueryDTO(dto.getPcode());
        SysAreaEntity father = Optional.ofNullable(this.getOne(wrapper(query)))
                .orElseThrow(() -> new ValidateCodeException("父地区不存在"));

        boolean unique = this.checkUniqueByAreaCode(dto.getId(), dto.getCode());
        if (!unique) {
            throw new ValidateCodeException("地区编码不唯一");
        }
        SysAreaEntity entity = SysAreaConvert.INSTANCE.update(dto);
        return this.updateById(entity);
    }

    @Override
    public Boolean remove(Long id) {
        List<SysAreaEntity> children = this.baseMapper.findChildrenById(id);
        if (CollectionUtils.isNotEmpty(children)) {
            throw new ValidateCodeException("子集不为空，不能删除");
        }
        return removeById(id);
    }

    private Boolean checkUniqueByAreaCode(Long id, String areaCode) {
        if (StringUtils.isEmpty(areaCode)) {
            return true;
        }

        LambdaQueryWrapper<SysAreaEntity> wrapper = Queries.lambda();
        Queries.accept(areaCode, v -> wrapper.eq(SysAreaEntity::getCode, v));

        Optional<SysAreaEntity> optional = Optional.ofNullable(this.getOne(wrapper));
        return optional.map(area -> Objects.equals(area.getId(), id)).orElse(true);
    }

    @Override
    public AreaResultVO getAreaDetail(AreaQueryDTO dto) {
        return SysAreaConvert.INSTANCE.convert(super.getOne(wrapper(dto)));
    }

    private LambdaQueryWrapper<SysAreaEntity> wrapper(AreaQueryDTO query) {
        LambdaQueryWrapper<SysAreaEntity> wrapper = Queries.lambda();
        Queries.accept(query.getCode(), v -> wrapper.eq(SysAreaEntity::getCode, v));
        Queries.accept(query.getPcode(), v -> wrapper.eq(SysAreaEntity::getPcode, v));
        Queries.accept(query.getAreaId(), v -> wrapper.eq(SysAreaEntity::getAreaId, v));
        Queries.accept(query.getName(), v -> wrapper.like(SysAreaEntity::getName, v));
        wrapper.orderByAsc(SysAreaEntity::getCode);
        return wrapper;
    }
}
